import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';
import queryLogsList from './service';

import contrast, { checkParams } from './contrast';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const stateInfo = {
  dataInfo: {
    list: [],
    count: 0,
  },
};

const Model: ModelType = {
  namespace: 'cabinetPlansLogsList',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryLogsList, payload);
      const data = fetchValidation(response);
      if (data) {
        const { body: { list, count } } = data;
        const dataList = list.map((item: any) => {
          const { map: { new: newInfo, old: oldInfo } } = item;
          const updateLogsInfo: any[] = Object.keys(newInfo).map((info: any) => {
            const oldValue = (oldInfo[info] !== null && typeof oldInfo[info] === 'object')
              ? oldInfo[info].name : checkParams(info, oldInfo[info]);
            const newValue = (newInfo[info] !== null && typeof newInfo[info] === 'object')
              ? newInfo[info].name : checkParams(info, newInfo[info]);
            return `${contrast[info]}的${oldValue}
            修改为${newValue}`.replace(/\s+/g, '');
          });
          return { ...item, logs: updateLogsInfo };
        });
        yield put({
          type: 'save',
          payload: {
            count,
            list: dataList,
          },
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },
  },
};

export default Model;
